package com.brkj.test;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import com.brkj.httpInterface.BaseAjaxParams;
import com.brkj.httpInterface.HttpInterface.HIF_GetExamDetail;
import com.brkj.main.R;
import com.brkj.test.model.DS_Exam;
import com.brkj.test.model.DS_Exam_detail_ques;
import com.brkj.test.model.DS_QuesRecord;
import com.brkj.util.ConstAnts;
import com.brkj.util.MyAjaxCallBack;
import com.brkj.util.Util;
import com.brkj.util.view.BaseActionBarActivity;
import com.brkj.util.view.BaseActivity;
import com.brkj.util.view.MyViewPager;
import com.brkj.util.view.WidgetAnim;
import com.dgl.sdk.util.DBStore;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import net.tsz.afinal.FinalDb;
import net.tsz.afinal.FinalHttp;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class ExamDetailWrongQuesActivity extends BaseActionBarActivity{

	private MyViewPager viewPager;
	private ArrayList<View> views = new ArrayList<View>();
	private ArrayList<QuestionItem> questionViewList = new ArrayList<QuestionItem>();
	private String examPaperID;
	
	private List<DS_Exam_detail_ques> quesList;
	
	private TextView doProgress;
	private TextView wrongNum;
	private TextView lastNum;
	
	private int quesHavedoNum = 1;
	private int quesTotalNum = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
        setAnimType(RIGHT_ENTER_LEFT_EXT);
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.test_exam_detail);
        setReturnBtn();

		viewPager = (MyViewPager) findViewById(R.id.viewPager);
		
		examPaperID = getIntent().getStringExtra("examId");

        setActivityTitle("错题练习");

//		setRightBtn("跳转试题", new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				SelectDoDialog dialog = new SelectDoDialog();
//				dialog.show();
//			}
//		});
		

		doProgress = (TextView) findViewById(R.id.doProgress);
		wrongNum = (TextView) findViewById(R.id.wrongNum);
		lastNum = (TextView) findViewById(R.id.lastNum);
        wrongNum.setVisibility(View.GONE);
		
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {
				quesHavedoNum = arg0 + 1;
				setQuesNum();
				
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				if((questionViewList.size()>0)
					&&(questionViewList.get(arg0)!=null)){
					questionViewList.get(arg0).clearAnswer();
				}
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});

        getExamDetail();
	}

	private void getExamDetail() {

        progressDialog.setMessage("正在读取数据...");
        progressDialog.show();

        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if((quesList != null) && (quesList.size()>0)){
                    quesTotalNum = quesList.size();
                    showQuestion();

                    setQuesNum();

                }else{
                    showToast("读取数据失败！");
                }

                progressDialog.dismiss();
            }
        };

        new Thread(){
            @Override
            public void run() {
                quesList = DBStore.readAll(DS_Exam_detail_ques.class,
                        ConstAnts.DB_TABLE_WRONGQUES+examPaperID);

                handler.sendEmptyMessage(0);
            }
        }.start();


	}


	protected void showQuestion() {
		for(int i=0; i<quesList.size(); i++){
			QuestionItem questionItem;
			if(i== (quesList.size()-1)){
				questionItem = new QuestionItem(quesList.get(i), true);
			}else{
				questionItem = new QuestionItem(quesList.get(i), false);
			}
			
			questionViewList.add(questionItem);
			
			views.add(questionItem.getView());
		}
		viewPager.setViews(views);
	}
	
	private void setQuesNum(){
		doProgress.setText("做题进度："+ quesHavedoNum + "/" + quesTotalNum );
		lastNum.setText("剩余："+ (quesTotalNum - quesHavedoNum) + "道");
	}


    private class QuestionItem{

        private View questionItemView;
        private DS_Exam_detail_ques quesItem;
        private boolean isCount = false;
        private boolean isDoWrong = false;
        private boolean isLast = false;
        private Question question;
        private int orig_quesWrongNum;
        private PopupWindow popupWindow;
        private Button popRedoBtn;
        private Button popNextBtn;
        private View popRightView;
        private View popWrongView;
        private TextView popAnswerText;

        public QuestionItem(final DS_Exam_detail_ques quesItem, boolean isLast){
            this.quesItem = quesItem;
            this.isLast = isLast;
        }

        public View getView(){

            question = new Question(ExamDetailWrongQuesActivity.this, quesItem);
            questionItemView = LayoutInflater.from(ExamDetailWrongQuesActivity.this).inflate(R.layout.test_exam_detail_ques_item, null);
            LinearLayout questionView = (LinearLayout) questionItemView.findViewById(R.id.questionView);
            Button submitAnswer = (Button) questionItemView.findViewById(R.id.submitAnswer);
            Button saveToWrongFolder = (Button) questionItemView.findViewById(R.id.saveToWrongFolder);


            initAnswerPopUpWindow();

            String answerStr;
            if(quesItem.getAnswer().equals("true")){
                answerStr =  "正确";
            }else if(quesItem.getAnswer().equals("false")){
                answerStr =  "错误";
            }else{
                answerStr = quesItem.getAnswer();
            }
            popAnswerText.setText(answerStr);


            saveToWrongFolder.setText("移出错题夹");
            saveToWrongFolder.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    ((TextView)v).setText("已移除");
                    v.setOnClickListener(null);
                    removeWrongQues(quesItem);
                }
            });

            if(isLast){
                popNextBtn.setText("学习完成");
                popNextBtn.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
            }else{
                popNextBtn.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        viewPager.goNext();
                        popupWindow.dismiss();
                    }
                });
            }
            popRedoBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    clearAnswer();
                    popupWindow.dismiss();
//					quesHavedoNum = orig_quesHavedoNum;
//					quesWrongNum = orig_quesWrongNum;
//					setQuesNum();
//					if(isDoWrong){
//						quesWrongNum--;
//						setQuesNum();
//					}
                }
            });


            submitAnswer.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if(question.getAnswer().equals("") ||
                            (question.getAnswer()== null)){
                        showToast("请先做题！");
                        return;
                    }

                    //如果后台没有传答案过来！防止崩溃
                    if(quesItem.Answer == null){
                        showToast("未获取到标准答案！");
                        return;
                    }

                    popupWindow.showAtLocation(viewPager, Gravity.CENTER, 0, 0);

                    if(quesItem.getAnswer().toLowerCase().equals(question.getAnswer().toLowerCase())){
//					if(question.getAnswer().contains(quesItem.getAnswer())){
                        popRightView.setVisibility(View.VISIBLE);
                        popWrongView.setVisibility(View.GONE);
                        isDoWrong = false;
                    }else{
                        popRightView.setVisibility(View.GONE);
                        popWrongView.setVisibility(View.VISIBLE);
                        isDoWrong = true;
                    };

                    if(!isCount){

                        setQuesNum();
                        isCount = true;
                    }



                }
            });
            questionView.addView(question.getView());


            return questionItemView;
        }

        private void initAnswerPopUpWindow(){

            View popupWindow_view = getLayoutInflater().inflate(
                    R.layout.test_answer_popupwindow, null, false);
            popupWindow = new PopupWindow(popupWindow_view,
                    RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT, false);// 鍒涘缓PopupWindow瀹炰緥

            popupWindow.setFocusable(true);
            popupWindow.setOutsideTouchable(true);
            // popupWindow.setAnimationStyle(R.style.PopWindowAnim);
            popupWindow.setBackgroundDrawable(new ColorDrawable(0));


            popRedoBtn = (Button) popupWindow_view.findViewById(R.id.redoBtn);
            popNextBtn = (Button) popupWindow_view.findViewById(R.id.nextBtn);
            popRightView = (View) popupWindow_view.findViewById(R.id.rightView);
            popWrongView = (View) popupWindow_view.findViewById(R.id.wrongView);
            popAnswerText = (TextView) popupWindow_view.findViewById(R.id.answerText);

        }

        //清除做题记录
        public void clearAnswer() {
            if(question != null){
                question.clearAnswer();
            }
        }

        //保存错题
        private void saveWrongQues(DS_Exam_detail_ques wrongQues){
            DBStore.save(wrongQues, ConstAnts.DB_TABLE_WRONGQUES + examPaperID);
        }

        //删除错题
        private void removeWrongQues(DS_Exam_detail_ques wrongQues){
            DBStore.delete(wrongQues, ConstAnts.DB_TABLE_WRONGQUES + examPaperID);
        }
    }

	
	public class SelectDoDialog {
		protected Button ok;
		protected Button cancle;
		protected EditText selectNum;
		protected TextView totalNumView;
		
		protected Dialog dialog;

		public SelectDoDialog() {
			dialog = new Dialog(ExamDetailWrongQuesActivity.this, R.style.MyCustomDialog);
			dialog.setContentView(R.layout.dialog_select_question);

			ok = (Button) dialog.findViewById(R.id.ok);
			cancle = (Button) dialog.findViewById(R.id.cancle);
			selectNum = (EditText) dialog.findViewById(R.id.selectNum);
			totalNumView = (TextView) dialog.findViewById(R.id.totalNum);
			
			totalNumView.setText("/" + quesTotalNum + "道");
			selectNum.setText(quesHavedoNum + "");
			
			cancle.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			
			ok.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(!WidgetAnim.checkIfEmpty(ExamDetailWrongQuesActivity.this, selectNum)){
						String seectNumText = selectNum.getText().toString();
						if(Util.isNumeric(seectNumText)
								&&(Integer.valueOf(seectNumText)<=quesTotalNum)){
							viewPager.setCurrentItem(Integer.valueOf(seectNumText) -1);
						}else{
							showToast("请输入有效的数字");
						}
						
					};
					dialog.dismiss();
				}
			});
		}
		
		
		public void show(){
			dialog.show();
		}
	}
	

	@Override
	public void finish() {

		Intent intent = new Intent();
		intent.setAction("com.brkj.examHaveDoneChanged");
		sendBroadcast(intent);
		
		super.finish();
		
		
	}


    private void showWrongQuesList(){
        Intent intent = new Intent(this, ExamWrongQuesActivity.class);
        intent.putExtra("examID", examPaperID);
        startActivity(intent);
    }

}
